import 'package:boss/color_constant.dart';
import 'package:boss/main.dart';
import 'package:boss/models/takeout_order_list_data.dart';
import 'package:boss/provider/takeout_process_provider.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/page/takeoutManagement/constant/takeout_status.dart';
import 'package:boss/ui/widget/alert/alert.dart';
import 'package:boss/ui/widget/button/outline_radius_button.dart';
import 'package:boss/ui/widget/button/radius_button.dart';
import 'package:boss/ui/widget/form/select_form_field.dart';
import 'package:boss/ui/widget/image/base_image.dart';
import 'package:boss/ui/widget/label_button.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:boss/ui/widget/modal/modal.dart';
import 'package:boss/ui/widget/radioList/model/radio_item_data.dart';
import 'package:boss/ui/widget/radioList/radio.dart' as radio;
import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

showRefundModal(
  BuildContext context, {
  TakeoutOrderItem data,
  List<TakeOutOrderDetails> selected,
  VoidCallback callback,
}) {
  showModal(
    context,
    builder: (context) => _RefundModal(
      data: data,
      selected: selected,
      callback: callback,
    ),
  );
}

class _RefundModal extends StatefulWidget {
  final TakeoutOrderItem data;
  final List<TakeOutOrderDetails> selected;
  final VoidCallback callback;

  const _RefundModal({
    Key key,
    this.data,
    this.selected,
    this.callback,
  }) : super(key: key);

  @override
  __RefundModalState createState() => __RefundModalState();
}

class __RefundModalState extends State<_RefundModal> {
  List<RadioItemData<TakeOutOrderDetails>> items = [];
  List<TakeOutOrderDetails> selected = [];
  List<String> reasons = [
    '商品临期编制/不新鲜/质量问题',
    '送错货',
    '全部商品未收到',
    '未在约定时间送达',
    '商品分量不足',
    '商品缺货',
    '实物和图文描述不符',
    '其他',
  ];
  String reason;

  List<SelectItem<String>> get reasonsForForm {
    return reasons.map((item) => SelectItem(title: item, value: item)).toList();
  }

  bool get isSelectedAll => selected.length == items.where((item) => item.value.status == 0).length;

  String get actionTitle => isSelectedAll ? '取消' : '全选';

  //是退款配送费
  bool retreatDeliveryFee = false;

  //是否存在优惠
  bool isFullDecrementDiscount = false;

  @override
  void initState() {
    super.initState();
    if (widget.selected != null) {
      selected = widget.selected;
    }

    items = widget.data.takeOutOrderDetails
        .map((item) => RadioItemData(
              title: item.title,
              value: item,
            ))
        .toList();

    if (widget.data.orderDiscountType != '' && widget.data.orderDiscountType != null && widget.data.orderDiscountType != 'no_discount') {
      isFullDecrementDiscount = true;
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 660.w,
      height: 800.w,
      padding: EdgeInsets.only(
        left: 30.w,
        right: 30.w,
        bottom: 30.w,
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          SelectFormField(
            title: '退款原因',
            hintText: '请选择',
            items: reasonsForForm,
            value: reason,
            onChanged: (value) {
              setState(() {
                reason = value;
              });
            },
          ),
          if (widget.data.type == TakeoutStatus.TAKEOUT)
            Container(
              decoration: BoxDecoration(
                border: Border(
                    bottom: BorderSide(
                  width: 1.px,
                  color: ColorConstant.e6e6,
                )),
              ),
              padding: EdgeInsets.symmetric(
                vertical: 36.w,
              ),
              child: Row(
                children: <Widget>[
                  Text(
                    "是否退款配送费",
                    style: TextStyleConstant().normal_1_28,
                  ),
                  Expanded(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        {"name": "退", "bool": true},
                        {"name": "不退", "bool": false},
                      ]
                          .map((e) => GestureDetector(
                                onTap: () {
                                  retreatDeliveryFee = e["bool"];
                                  setState(() {});
                                },
                                child: Row(
                                  children: <Widget>[
                                    radio.Radio(
                                      isSelected: retreatDeliveryFee == e["bool"],
                                    ),
                                    Text(
                                      "  ${e["name"]}",
                                      style: TextStyleConstant().normal_2_28,
                                    )
                                  ],
                                ),
                              ))
                          .toList(),
                    ),
                  ),
                ],
              ),
            ),
          Padding(
            padding: EdgeInsets.only(
              top: 12.w,
              bottom: 12.w,
            ),
            child: Row(
              children: <Widget>[
                Spacer(),
                RichText(
                  text: TextSpan(children: <TextSpan>[
                    TextSpan(
                      text: "退款菜品",
                      style: TextStyleConstant().normal_1_32,
                    ),
                    TextSpan(
                      text: "${isFullDecrementDiscount ? '（优惠）' : ''}",
                      style: TextStyleConstant().origin_32,
                    ),
                  ]),
                ),
                Expanded(
                  child: Align(
                    alignment: Alignment.centerRight,
                    child: LabelButton(
                      title: actionTitle,
                      onTap: () {
                        setState(() {
                          selected = isSelectedAll ? [] : items.where((item) => item.value.status == 0).map((item) => item.value).toList();
                        });
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            padding: EdgeInsets.only(
              top: 16.w,
              bottom: 8.w,
            ),
            child: DefaultTextStyle(
              style: TextStyleConstant().normal_2_26,
              child: Row(
                children: <Widget>[
                  SizedBox(
                    width: 50.w,
                  ),
                  Expanded(
                    child: Text("菜品"),
                    flex: 2,
                  ),
                  Expanded(
                    child: Text("数量"),
                  ),
                  Expanded(
                    child: Text("包装费"),
                  ),
                  Expanded(
                    child: Text("售价"),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            child: ListView.builder(
              padding: EdgeInsets.only(),
              itemCount: widget.data.takeOutOrderDetails.length,
              itemBuilder: (context, index) {
                var current = widget.data.takeOutOrderDetails[index];
                var isSelected = selected.contains(current);

                return _RadioItem(
                  data: current,
                  isSelected: isSelected,
                  onTap: () {
                    setState(() {
                      isSelected ? selected.remove(current) : selected.add(current);
                    });
                  },
                );
              },
            ),
          ),
          SizedBox(
            height: 12.w,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              OutlineRadiusButton(
                title: '取消',
                onTap: () {
                  Navigator.pop(context);
                },
              ),
              RadiusButton(
                title: '确认',
                onTap: () async {
                  if (reason == null) {
                    toast('请选择退款原因');
                    return;
                  }
                  if (selected.length == 0) {
                    toast('请选择需要退菜的菜品');
                    return;
                  }
                  Navigator.pop(context);

                  var isAll = selected.length == widget.data.takeOutOrderDetails.length;

                  int price = 0;
                  if (isFullDecrementDiscount == true) {
                    //存在满减优惠
                    try {
                      showLoadingToast();
                      var res = await api.calRefundMoneyVO({
                        'takeOutId': (widget.data.takeOutId),
                        'type': isAll ? 0 : 1, //0全额退款1部分退款,
                        'orderDetailIdList': (selected.map((item) => item.id).toList()),
                      });
                      if (!res.successful()) {
                        price = await (res.data['totalAmount'] ?? 0);
                        if (retreatDeliveryFee == true) {
                          price = (price + (res.data["deliverFee"] ?? 0));
                        }
                        confirmRefundAlert(
                          GlobalPageContext.instance.context,
                          price: price,
                          takeOutId: widget.data.takeOutId,
                          status: widget.data.systemOrderStatus,
                          reason: reason,
                          orderDetailList: selected,
                          type: isAll ? 0 : 1,
                        );
                      } else {
                        toast(res.msg);
                      }
                    } catch (e) {} finally {
                      hideLoadingToast();
                    }
                  } else {
                    //无满减优惠
                    selected.forEach((item) {
                      price += (item.actualFee + item.packFee);
                    });
                    if (retreatDeliveryFee == true) {
                      price = price + (widget.data.deliverFee ?? 0);
                    }
                    confirmRefundAlert(
                      context,
                      price: price,
                      takeOutId: widget.data.takeOutId,
                      status: widget.data.systemOrderStatus,
                      reason: reason,
                      orderDetailList: selected,
                      type: isAll ? 0 : 1,
                    );
                  }
                },
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class _RadioItem extends StatelessWidget {
  final TakeOutOrderDetails data;
  final bool isSelected;
  final VoidCallback onTap;

  const _RadioItem({
    Key key,
    this.data,
    this.isSelected = false,
    this.onTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (data.status == 0) {
          onTap();
        }
      },
      child: DefaultTextStyle(
        style: TextStyleConstant().normal_1_28,
        child: Container(
          height: 110.w,
          decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(width: 1.px, color: ColorConstant.e6e6),
            ),
          ),
          alignment: Alignment.center,
          child: Stack(
            children: <Widget>[
              Row(
                children: <Widget>[
                  if (data.status == 1)
                    BaseImage(
                      'assets/image/order_retreat.png',
                      width: 40.w,
                      height: 40.w,
                    ),
                  if (data.status == 0)
                    radio.Radio(
                      isSelected: isSelected,
                    ),
                  SizedBox(
                    width: 15.w,
                  ),
                  Expanded(
                    flex: 2,
                    child: Text(data.title),
                  ),
                  Expanded(
                    child: Text('x' + data.num.toString()),
                  ),
                  Expanded(
                    child: Text('¥' + AmountUtil.price2String(data.packFee)),
                  ),
                  Expanded(
                    child: Text('¥' + AmountUtil.price2String(data.actualFee)),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

confirmRefundAlert(
  BuildContext context, {
  int price,
  String takeOutId,
  String reason,
  int status,
  List<TakeOutOrderDetails> orderDetailList,
  int type,
}) {
  showAlert(
    context,
    content: '确认退款${AmountUtil.price2String(price)}元给客户吗？',
    onCancel: (context) {
      Navigator.pop(context);
    },
    onConfirm: (context) async {
      Navigator.pop(context);

      var provider = Provider.of<TakeoutProcessProvider>(
        GlobalPageContext.instance.context,
        listen: false,
      );

      provider.storeRefund(
        takeOutId: takeOutId,
        orderDetailList: orderDetailList,
        reason: reason,
        status: status,
        type: type,
      );
    },
  );
}
